'use strict';
const db = uniCloud.database();
const collection = db.collection('user');
const crypto = require('crypto')
exports.main = async (event, context) => {
	let md5 = crypto.createHash('md5');
	var res = {
		"code": "0000",
		"data": {
			"state": 0,
			"msg": "账号不存在"
		}
	};
	//console.log(event.data);
	//查询这个用户信息
	let user_info = await collection.where({
		name: event.data.name
	}).get();
	//console.log(user_info.data[0]);
	if (user_info.data[0]) {
        md5.update(event.data.password);//加密
		let md5_password = md5.digest('hex');
		event.data.password = md5_password
		if (user_info.data[0].password == event.data.password) { //正确则登录成功
			//生成token 随机数+时间戳+uid
			var timestamp = (new Date()).valueOf(); //获取当前毫秒的时间戳
			let str_token = Math.floor(Math.random() * 10000) + timestamp;
			//将token写入数据集
			collection.where({
				name: event.data.name,
				password: event.data.password
			}).update({
				token: str_token,
				token_time: timestamp
			});
			user_info.data[0].token = str_token;
			res.data.msg = "登录成功";
			res.data.user_info = user_info.data[0];
			res.data.state = 1;
		} else {
			res.data.state = 2;
			res.data.msg = "密码错误";
		}

	}
	return res;
};

